# -*- coding: utf-8 -*-
# auth: wujian 2022.09.23
# python -m nuitka --lto=no --onefile --standalone xx
# 导入程序运行必须模块
import re
#import socket
import sys
import os
import time
import telnetlib

HOST = "192.168.10.1"
PORT = 5504
PWD1 = 'bRysj,hHrhl'
PWD2 = 'yQqlm,gSycl'
AT1 = 'at+system=uci set dropbear.@dropbear[0].enable=1;uci commit'
AT2= 'at+system=/etc/init.d/dropbear start'

def do_my_telnet_cmd():
    at_ack = b'OK'
    flg = 0
    try:
        # 连接Telnet服务器
        tn = telnetlib.Telnet(HOST, port=PORT, timeout=5)
        # for debug
        # tn.set_debuglevel(2)
        # 登录完毕后执行命令
        time.sleep(0.5)
        # 登录完毕后执行命令
        result = tn.write(PWD1.encode('ascii') + b'\r')
        time.sleep(0.5)
        result = tn.write(PWD2.encode('ascii') + b'\r')
        time.sleep(0.5)
        
        result = tn.write(AT1.encode('ascii') + b'\r')
        result = tn.read_until(at_ack, 10)
        print('recv:', result.decode('ascii'))
        if result :
            flg += 1
            #print(f"AT send {AT1} ok")
        
        result = tn.write(AT2.encode('ascii') + b'\r')
        result = tn.read_until(at_ack, 10)
        print('recv:', result.decode('ascii'))
        if result :
            flg += 1
            #print(f"AT send {AT2} ok")
        # 执行完毕后，终止Telnet连接（或输入exit退出）
        tn.close()  # tn.write('exit\n')
        if flg == 2:
            print(f"enable ssh success\r")
        else:
            print(f"enable ssh fail.\r")
    except Exception as e:
        print("telnet error: ", e)
    return at_ack

def main():
    do_my_telnet_cmd()

if __name__ == "__main__":
    main()
    input("Press Enter to exit...")
